package cn.owen.controller;

import java.util.Date;

import cn.owen.model.User;
import cn.owen.service.UserService;
import cn.owen.util.CurrentUserUtils;
import cn.owen.util.MD5Utils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
/**
 * 
 * @author Burning
 * @email wenbao163.good@163.com
 * @date 2016年9月27日下午11:01:02
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    
    @RequestMapping("/list")
	 public String selectList(User users,@RequestParam(defaultValue="1") String pageNum,
				@RequestParam(defaultValue="10") String pageSize,Model model) {
		 User user=CurrentUserUtils.getInstance().getUser();
		 PageInfo<User> page=userService.selectPageUser(pageNum,pageSize, users);
		 model.addAttribute("page", page);
		 model.addAttribute("user", user);
		 model.addAttribute("users", users);
		 return "admin/user/list";
	 }
    
    @RequestMapping("toAdd")
    public String toAdd(){
    	return "admin/user/add";
    }
    
    @RequestMapping("toEdit")
    public String toEdit(Model model ,String id){
    	User user = new User();
    	if(id!=null){
    		user=userService.selectById(Integer.valueOf(id));
		 }
		 model.addAttribute("user", user);
		 return "admin/user/edit";
    }
    
    @RequestMapping("save")
	public String save(User users,Model model){
		 User user=CurrentUserUtils.getInstance().getUser();
		 if(users.getId()!=null&&users.getId()!=0){
			 userService.update(users);
		 }else{
			 users.setPassword(MD5Utils.getMD5StringBySign("654321"));
			 users.setCreatename(user.getName());
			 users.setCreatetime(new Date());
			 userService.insert(users);
		 }
		 return "redirect:/user/list";
	}
    
    @RequestMapping("delete")
    public String delete(Model model ,String id){
    	if(id!=null){
    		userService.delete(Integer.valueOf(id));
		 }
    	 return "redirect:/user/list";
    }
    
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public User getUserInfo() {
        User user = userService.getUserInfo("","");
        if(user!=null){
            System.out.println("user.getName():"+user.getName());
            logger.info("user.getAge():"+user.getAge());
        }
        return user;
    }
}
